require 'file_analyser'

class Backup
  
  attr_reader :name
  attr_reader :root, :file_delimiter
  attr_reader :directories
  attr_reader :qualified_directories
  
  #``````````````````
  # constructor
  #``````````````````

  def initialize(name,root)
    @name = name
    @root,@file_delimiter = fix_qualified root
    @qualified_directories = []
    @directories = []
  end
  
  #``````````````````
  # interface
  #``````````````````
  
  def has_name?
    @name.length > 0
  end
  
  def add_directory(new_directory)
    fixed_directory = fix(new_directory)
    @directories << fixed_directory
    @qualified_directories << "#{@root}#{fixed_directory}"
  end
  
  def add_qualified_directory(new_directory)
    add_directory new_directory[@root.length..-1]
  end
  
  def remove_directory(existing_directory)
    fixed_directory = fix existing_directory
    index = @directories.index fixed_directory
    
    unless index.nil?
      @directories.delete_at index
      @qualified_directories.delete_at index
    end
  end
  
  
  def qualified_directory_of(directory)
    @qualified_directories[@directories.index(directory)]
  end
  
  #``````````````````
  # private methods
  #``````````````````  
  
  private
   
    def fix_qualified(root)
      last_character = root[-1..-1]
      if FileAnalyser.file_delimiter? last_character
        root = root[0...-1]
      end
      return [root, FileAnalyser.file_delimiter_for(root)]
    end
    
    def fix(directory)
      first_character = directory[0..0]
      if FileAnalyser.file_delimiter? first_character
        directory = directory[1..-1]
      end
      last_character = directory[-1..-1]
      if FileAnalyser.file_delimiter? last_character
        directory = directory[0...-1]
      end
      "#{@file_delimiter}#{directory}"
    end
  
end
